<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Download, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import DriverDialog from '@/components/DriverDialog.vue';
import { dataAPI } from '@/http/leancloud';

/**
 * 此页面对应承运管理下的 司机管理
 */
// 查询条件
const queryForm = reactive({
  driverName: '', // 司机姓名
  phone: '', // 手机号
  idCard: '', // 身份证号
  licenseType: '', // 驾照类型
  status: '' // 状态
});

// 表格数据
const tableData = ref<any[]>([]);
// 表格加载状态
const loading = ref(false);
// 表格选中的行
const selectedRows = ref<any[]>([]);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 驾照类型选项
const licenseTypeOptions = [
  { value: 'A1', label: 'A1' },
  { value: 'A2', label: 'A2' },
  { value: 'B1', label: 'B1' },
  { value: 'B2', label: 'B2' },
  { value: 'C1', label: 'C1' },
  { value: 'C2', label: 'C2' }
];

// 状态选项
const statusOptions = [
  { value: 1, label: '在职' },
  { value: 0, label: '离职' },
  { value: 2, label: '停职' }
];

// 字段转换：前端 -> LeanCloud
const convertToLeanCloudData = (data: any, isEdit: boolean = false) => {
  const leancloudData: any = {
    name: data.driverName,
    company: data.company,
    phone: data.phone,
    idCard: data.idCard,
    licenseType: data.licenseType,
    licenseExpiry: data.licenseExpiry ?
      (typeof data.licenseExpiry === 'string' ? { __type: 'Date', iso: new Date(data.licenseExpiry).toISOString() } : data.licenseExpiry)
      : undefined,
    qualificationExpiry: data.qualificationExpiry ?
      (typeof data.qualificationExpiry === 'string' ? { __type: 'Date', iso: new Date(data.qualificationExpiry).toISOString() } : data.qualificationExpiry)
      : undefined,
    address: data.homeAddress,
    emergencyContact: data.emergencyContact,
    emergencyPhone: data.emergencyPhone,
    price: data.price ? Number(data.price) : undefined,
    remark: data.remark,
    status: Number(data.status)
  };
  if (isEdit) leancloudData.objectId = data.id;
  return leancloudData;
};

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    const drivers = await dataAPI.query('Driver');
    tableData.value = drivers.map((driver: any) => {
      const status = typeof driver.status === 'string' ? parseInt(driver.status) : driver.status;
      return {
        id: driver.objectId,
        driverName: driver.name,
        company: driver.company,
        phone: driver.phone,
        idCard: driver.idCard,
        licenseType: driver.licenseType,
        licenseExpiry: driver.licenseExpiry && driver.licenseExpiry.iso ? driver.licenseExpiry.iso.slice(0, 10) : '',
        qualificationExpiry: driver.qualificationExpiry && driver.qualificationExpiry.iso ? driver.qualificationExpiry.iso.slice(0, 10) : '',
        homeAddress: driver.address,
        emergencyContact: driver.emergencyContact,
        emergencyPhone: driver.emergencyPhone,
        price: driver.price,
        status: status,
        remark: driver.remark,
        createTime: driver.createdAt ? new Date(driver.createdAt).toLocaleString() : '',
        updateTime: driver.updatedAt ? new Date(driver.updatedAt).toLocaleString() : ''
      };
    });
    pagination.total = drivers.length;
  } catch (error) {
    console.error('获取司机数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQueryForm = () => {
  Object.keys(queryForm).forEach(key => {
    (queryForm as any)[key] = '';
  });
  handleSearch();
};

// 查询数据
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTableData();
};

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 处理分页变化
const handlePageChange = (currentPage: number) => {
  pagination.currentPage = currentPage;
  fetchTableData();
};

// 处理每页条数变化
const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.currentPage = 1;
  fetchTableData();
};

// 对话框相关状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentDriver = ref<any>(null);

// 新增司机
const handleAdd = () => {
  isEdit.value = false;
  currentDriver.value = null;
  dialogVisible.value = true;
};

// 编辑司机
const handleEdit = (row: any) => {
  isEdit.value = true;
  currentDriver.value = { ...row };
  dialogVisible.value = true;
};

// 删除司机
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除司机"${row.driverName}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await dataAPI.delete('Driver', row.id);
      const index = tableData.value.findIndex(item => item.id === row.id);
      if (index > -1) {
        tableData.value.splice(index, 1);
        pagination.total--;
      }
      ElMessage.success('删除成功');
    } catch (error) {
      console.error('删除司机失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 处理对话框确认
const handleDialogConfirm = async (data: any) => {
  try {
    const leancloudData = convertToLeanCloudData(data, isEdit.value);
    if (isEdit.value) {
      const result = await dataAPI.save('Driver', leancloudData);
      if (!result || !result.objectId) {
        ElMessage.error('保存失败，未返回ID');
        return;
      }
      fetchTableData();
    } else {
      const result = await dataAPI.save('Driver', leancloudData);
      if (!result || !result.objectId) {
        ElMessage.error('保存失败，未返回ID');
        return;
      }
      fetchTableData();
    }
  } catch (error: any) {
    console.error('保存司机数据失败:', error);
    ElMessage.error('保存失败: ' + (error.message || error));
  }
};

// 导入数据
const handleImport = () => {
  console.log('导入数据');
};

// 导出数据
const exportData = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要导出的记录');
    return;
  }
  console.log('导出数据', selectedRows.value);
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}条记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功');
    fetchTableData();
  }).catch(() => {});
};

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'success';
    case 0:
      return 'danger';
    case 2:
      return 'warning';
    default:
      return 'info';
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchTableData();
});
</script>

<template>
  <div class="driver-manage-view">
    <div class="page-header">
      <h2 class="page-title">司机管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryForm" inline>
        <el-form-item label="司机姓名">
          <el-input v-model="queryForm.driverName" placeholder="请输入司机姓名" clearable></el-input>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="queryForm.phone" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>

        <el-form-item label="身份证号">
          <el-input v-model="queryForm.idCard" placeholder="请输入身份证号" clearable></el-input>
        </el-form-item>

        <el-form-item label="驾照类型">
          <el-select v-model="queryForm.licenseType" placeholder="请选择" clearable>
            <el-option
              v-for="item in licenseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <div class="left">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button :icon="Download" @click="handleImport">导入</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </div>
      <div class="right">
        <el-button :icon="Download" @click="exportData">导出</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="driverName" label="姓名" width="100" />
      <el-table-column prop="company" label="物流公司" width="120" />
      <el-table-column prop="phone" label="手机号" width="150" />
      <el-table-column prop="idCard" label="身份证号" width="120" />
      <el-table-column prop="licenseType" label="驾照类型" width="100">
        <template #default="{ row }">
          <el-tag type="info">{{ row.licenseType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="licenseExpiry" label="驾照有效期" width="120" />
      <el-table-column prop="homeAddress" label="家庭住址" min-width="120" show-overflow-tooltip />
      <el-table-column prop="emergencyContact" label="紧急联系人" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ statusOptions.find(item => item.value == row.status)?.label || `未知状态(${row.status})` }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{ row }">
          <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="primary" link>详情</el-button>
          <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 司机对话框 -->
    <DriverDialog
      v-model:visible="dialogVisible"
      :driver-data="currentDriver"
      :is-edit="isEdit"
      @confirm="handleDialogConfirm"
    />
  </div>
</template>

<style scoped>
.driver-manage-view {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}

.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>